import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';

import QueueAnim from 'rc-queue-anim'
import TweenOne from 'rc-tween-one'

import { connect } from 'dva';

import { Row, Col, Card, Form, Input, Select, Icon, Button, Dropdown, Menu, InputNumber, DatePicker, Modal, message, Badge, Divider, Steps, Radio, } from 'antd';

import MyIcon from '@/components/MyIcon';
import DescriptionList from '@/components/DescriptionList';

import StandardTable from '@/containers/StandardTable';
import StandardTableForm from '@/containers/StandardTable/StandardTableForm';
import StandardTableHandle from '@/containers/StandardTable/StandardTableHandle';

import { userGoods as columns } from '@/commons/columns';
import { userGoods as map } from '@/commons/map';

import styles from './Goods.less';

const { Description } = DescriptionList;

const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
  .map(key => obj[key])
  .join(',');

/* eslint react/no-multi-comp:0 */
@connect(({ userGoods, loading }) => ({
  userGoods,
  loading: loading.models.userGoods,
}))
@Form.create()
class TableList extends PureComponent {
  state = {
    expandForm: false,
    formValues: {},
    status: '0',
    id: 0,
  };

  columns = [...columns, {
    title: '操作',
    width: 99,
    align: 'center',
    fixed: 'right',
    render: ({ id, status }, record) => (<Button icon="edit" type="primary" size="small" disabled={status} onClick={() => this.handleModalVisible(true, id)}>{status ? '已阅' : '已阅'}</Button>),
  }];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'userGoods/fetch',
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      from: pagination.current,
      size: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'userGoods/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'userGoods/fetch',
      payload: {},
    });
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  handleMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;
    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'userGoods/remove',
          payload: { id: selectedRows.map(row => row.id) },
          callback: ({ errno, data }) => {
            if (!errno && data) {
              dispatch({
                type: 'userGoods/fetch'
              });
              this.setState({
                selectedRows: []
              });
              message.success(`删除成功 ${data} 条`);
            } else {
              message.error('删除失败！');
            }
          },
        });
        break;
      case 'update':
        dispatch({
          type: 'userGoods/update',
          payload: { id: selectedRows.map(row => row.id) },
          callback: ({ errno, data }) => {
            if (errno) {
              message.error('更新失败！');
            } else {
              dispatch({
                type: 'userGoods/fetch'
              });
              this.setState({
                selectedRows: []
              });
              message.success('更新成功！');
            }
          },
        });
        break;
      default:
        break;
    }
  };

  handleSelectRows = rows => {
    this.setState(state => ({
      ...state,
      selectedRows: rows,
    }));
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        createdAt: fieldsValue.createdAt && fieldsValue.createdAt.valueOf(),
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'userGoods/fetch',
        payload: values,
      });
    });
  };

  handleModalVisible = (flag, id) => {
    this.setState({
      modalVisible: !!flag,
      id
    });
  };

  handleUpdate = ({ remark }) => {
    const { dispatch } = this.props;
    const { id } = this.state;

    dispatch({
      type: 'userGoods/update',
      payload: { id, remark },
      callback: ({ errno, data }) => {
        if (errno) {
          message.error('更新失败！');
        } else {
          dispatch({
            type: 'userGoods/fetch'
          });
          message.success('更新成功！');
        }
      }
    });

    this.handleModalVisible();
  };

  renderTable = e => {
    e.preventDefault();

    const { dispatch } = this.props;

    this.setState(state => ({ ...state, status: e.target.value }), () => {
      const { status } = this.state;
      dispatch({
        type: 'userGoods/fetch',
        payload: {
          status,
        }
      });
    });
  }

  render() {
    const { userGoods: { data, status }, loading, form, queryRow = {} } = this.props;
    const { expandForm } = this.state;

    console.log(queryRow, 'queryRow')

    return (
      <Card bordered={false}>
        <DescriptionList size="large" title="奖品详情" style={{ marginBottom: 16 }}>
          <Description term="用户昵称">{queryRow.nickname}</Description>
          <Description term="首次登录时间">{moment(queryRow.createdAt).format('YYYY-MM-DD HH:mm')}</Description>
          <Description term="最近登录时间">{moment(queryRow.updatedAt).format('YYYY-MM-DD HH:mm')}</Description>
          <Description term="当前幸运草数量">{queryRow.amount}</Description>
          <Description term="总获得幸运草数">{queryRow.totalIn}</Description>
        </DescriptionList>
        <StandardTableForm
          expandForm={expandForm}
          data={map}
          form={form}
          onSubmit={this.handleSearch}
          onReset={this.handleFormReset}
          onToggle={this.toggleForm}
        />
        <StandardTableHandle
          status={String(status)}
          radioGroups={{
            'all': <Fragment><MyIcon type="icon-all" />&nbsp;参与抽奖</Fragment>,
            '0': <Fragment><MyIcon type="icon-review" />&nbsp;发起抽奖</Fragment>,
            '1': <Fragment><MyIcon type="icon-preview" />&nbsp;中奖纪录</Fragment>,
          }}
          action={<a href="/favicon.png" target="_blank"><Button type="primary" icon="download">EXCEL</Button></a>}
          onToggleTable={this.handleToggleTable}
          onMenuClick={this.handleMenuClick}
        />
        <StandardTable
          loading={loading}
          data={data}
          bordered={true}
          size="small"
          scroll={{ x: 1300 }}
          columns={this.columns}
          onChange={this.handleStandardTableChange}
          rowSelection={null}
        />
      </Card>
    );
  }
}

export default TableList;